package com.example.gramediamajalahmobile.main;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.gramediamajalahmobile.R;

public class LazyAdapter extends BaseAdapter {

	private Activity activity;
	private ArrayList<HashMap<String, String>> data;
	private static LayoutInflater inflater = null;
	private URL url;
	private Bitmap bmp;

	public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
		activity = a;
		data = d;
		inflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public int getCount() {
		return data.size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View vi = convertView;
		if (convertView == null)
			vi = inflater.inflate(R.layout.row, null);
		TextView title = (TextView) vi.findViewById(R.id.title);
		TextView shortdesc = (TextView) vi.findViewById(R.id.shortdesc);
		TextView id = (TextView) vi.findViewById(R.id.id);
		ImageView image = (ImageView) vi.findViewById(R.id.images);

		HashMap<String, String> articles = new HashMap<String, String>();
		articles = data.get(position);
		// Setting all values in listview
		title.setText(articles.get(Article.AR_JUDUL));
		id.setText(articles.get(Article.AR_ID));
		shortdesc.setText(articles.get(Article.AR_SHORDESC));

		try {
			url = new URL(articles.get(Article.AR_IMAGE));
			bmp = BitmapFactory.decodeStream(url.openConnection()
					.getInputStream());
			image.setImageBitmap(bmp);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return vi;
	}
}